#!/bin/bash

set -eux
### --start_docs

## * Source in the undercloud credentials.
## ::

source {{ working_dir }}/stackrc

## * Introspect hardware attributes of nodes.
## ::
openstack overcloud node introspect --all-manageable
openstack overcloud node provide --all-manageable

{% if step_introspect_with_retry|bool %}

## * Introspect all manageable nodes with a caller provided timeout.
##   then move all nodes that power off after a successful introspection
##   back to available so we don't introspect them again. This is useful
##   for large deployments (think 10+ nodes) where bulk introspection
##   can be troublesome. It's also useful in environments where connection
##   problems may spuriously fail a deployment. Related-Bug: #1651127
## ::
introspect()
{
    for node in `openstack baremetal node list -f json | jq -r '.[]| select(.["Provisioning State"] == "manageable")| .["UUID"]'`; do
        openstack baremetal introspection start $node
        sleep 30s
    done

    manageable_count=1
    on_count=0
    while [ $on_count -eq 0 ] && [ $manageable_count -gt 0 ]; do
        manageable_count=$(openstack baremetal node list -f json | jq -r '.[]| select(.["Provisioning State"] == "manageable")| .["UUID"]' | wc -l)
        on_count=$(openstack baremetal node list -f json|jq -r '.[]| select(.["Power State"] == "power on")| .["UUID"]' | wc -l)
        sleep 30
    done

    set +e
    timeout $1 bash -c -- 'source {{ working_dir }}/stackrc; \
                            on_count=$(openstack baremetal node list -f json|jq -r ".[]| select(.[\"Power State\"] == \"power on\")| .[\"UUID\"]" | wc -l) ; \
                            while [ $on_count -gt 0 ]; do \
                                sleep 30s; \
                                on_count=$(openstack baremetal node list -f json|jq -r ".[]| select(.[\"Power State\"] == \"power on\")| .[\"UUID\"]" | wc -l) ; \
                            done'
    set -e

    for node in `openstack baremetal node list -f json | jq -r '.[]| select(.["Power State"] == "power off")| select(.["Provisioning State"] == "manageable")|.["UUID"]'`; do
        openstack baremetal node provide $node
    done
}

## * Introspect hardware attributes of nodes in a robust manner
##   retrying up to three times on any given node. This should
##   only be used in cases where deployment using bulk introspection
##   has reliability issues.
## ::

for node in `openstack baremetal node list -f json | jq -r '.[]| select(.["Provisioning State"] == "available")| .["UUID"]'`; do
    openstack baremetal node manage $node
done

introspect 15m
introspect 30m
introspect 60m

{% endif %}

### --stop_docs
